<template>
  <div class="infinite-viewport" @mousedown="startDrag" @mouseup="endDrag" @mousemove="dragging" @wheel="zoom">
    <div class="content" :style="{ transform: `scale(${scale}) translate(${translateX}px, ${translateY}px)` }">
      <!-- 在这里添加你的页面区域内容 -->
<!--      <node></node>-->
      <slot></slot>
    </div>
  </div>
</template>

<script>
import Node from '../../test/canvas/node'

export default {
  name: 'area',
  components: {
    // Node
  },

  data() {
    return {
      scale: 1,
      translateX: 0,
      translateY: 0,
      isDragging: false,
      startDragX: 0,
      startDragY: 0
    };
  },
  methods: {
    startDrag(event) {
      this.isDragging = true;
      this.startDragX = event.clientX;
      this.startDragY = event.clientY;
    },
    endDrag() {
      this.isDragging = false;
    },
    dragging(event) {
      if (this.isDragging) {
        const deltaX = event.clientX - this.startDragX;
        const deltaY = event.clientY - this.startDragY;
        this.startDragX = event.clientX;
        this.startDragY = event.clientY;
        this.translateX += deltaX;
        this.translateY += deltaY;
      }
    },
    zoom(event) {
      event.preventDefault();
      const zoomSpeed = 0.1;
      const oldScale = this.scale;
      if (event.deltaY < 0) {
        // 放大
        this.scale = Math.min(3, this.scale + zoomSpeed);
      } else {
        // 缩小
        this.scale = Math.max(0.2, this.scale - zoomSpeed);
      }

      // 调整translateX和translateY以保持焦点位置不变
      // this.translateX += (event.clientX - this.$el.getBoundingClientRect().left) * (1 / oldScale - 1 / this.scale);
      // this.translateY += (event.clientY - this.$el.getBoundingClientRect().top) * (1 / oldScale - 1 / this.scale);

      // 计算最大可偏移量，防止超出左上方边界
      const maxTranslateX = 0;
      const maxTranslateY = 0;
      // 调整translateX和translateY以保持内容不超出左上方边界
      this.translateX = Math.min(maxTranslateX, Math.max(this.translateX, -maxTranslateX));
      this.translateY = Math.min(maxTranslateY, Math.max(this.translateY, -maxTranslateY));
    }
  }
};
</script>

<style scoped>
.infinite-viewport {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  cursor: grab;
}

.content {
  width: 100%;
  height: 100%;
  transform-origin: top left;
  user-drag: none;
  user-select: none;
}
</style>
